package com.ruanxie.utils;

import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

public class ImageUtil {
    //这个方法我就先不分解了

    /**
     * 根据(xCenter,yCenter,width,height)裁剪filePath对应的图片，返回base64字符串
     * @param filePath
     * @param xCenter
     * @param yCenter
     * @param width
     * @param height
     * @return
     * @throws IOException
     */
    public static String imageSplitToBase64(String filePath,double xCenter,double yCenter,double width,double height) throws IOException {
        //读取图片
        BufferedImage image= ImageIO.read(new File(filePath  ));

        // 图片的宽度和高度
        int imgWidth = image.getWidth();
        int imgHeight = image.getHeight();

//            label: 1 0.476773 0.508242 0.953545 0.983516
//            0 0.57335 0.121566 0.320293 0.188187
//        // 给定的中心坐标、宽度和高度
//        double xCenter = 0.57335; // 中心x坐标 (相对于图片宽度)
//        double yCenter = 0.121566; // 中心y坐标 (相对于图片高度)
//        double width = 0.320293;   // 宽度 (相对于图片宽度)
//        double height = 0.188187;  // 高度 (相对于图片高度)

        // 将中心点和宽高转换为像素坐标
        int cropWidth = (int) (width * imgWidth);
        int cropHeight = (int) (height * imgHeight);
        int x = (int) (xCenter * imgWidth - cropWidth / 2);
        int y = (int) (yCenter * imgHeight - cropHeight / 2);

        // 确保坐标不会超出图片边界
        x = Math.max(0, x);
        y = Math.max(0, y);
        cropWidth = Math.min(cropWidth, imgWidth - x);
        cropHeight = Math.min(cropHeight, imgHeight - y);

        // 分割图片
        BufferedImage croppedImage = image.getSubimage(x, y, cropWidth, cropHeight);

//        // 保存分割后的图片
//        File outputFile = new File("cropped_image.jpg");
//        ImageIO.write(croppedImage, "jpg", outputFile);
//
//        System.out.println("图片分割完成并保存成功！");

        //将BufferedImage转为base64
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(croppedImage,"jpg",stream);
        byte[] bytes = Base64.encodeBase64(stream.toByteArray());
        String base64 = new String(bytes);
//        System.out.println(base64);
        return base64;
    }
}
